package com.deep.test.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TCPProtocolImpl implements TCPProtocol {
	private int bufferSize=2048;  
	public TCPProtocolImpl(int bufferSize){
		this.bufferSize = bufferSize;
	}
	public TCPProtocolImpl(){}
	public void handleAccept(SelectionKey selectionKey) throws IOException {
		SocketChannel clientChannel = ((ServerSocketChannel) selectionKey.channel()).accept();  
        clientChannel.configureBlocking(false);  
        clientChannel.register(selectionKey.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));  
        System.out.println(selectionKey.attachment() + " - 已连接");

	}

	public void handleRead(SelectionKey key) throws IOException {
		// 获得与客户端通信的信道  
        SocketChannel clientChannel = (SocketChannel) key.channel();  
  
        // 得到并清空缓冲区  
        ByteBuffer buffer = (ByteBuffer) key.attachment();  
        buffer.clear();  
  
        // 读取信息获得读取的字节数  
        long bytesRead = clientChannel.read(buffer);  
  
        if (bytesRead == -1) {  
            // 没有读取到内容的情况  
            clientChannel.close();  
        } else {  
            // 将缓冲区准备为数据传出状态  
            buffer.flip();  
  
            String receivedString = MessageConvertUtil.decodeString(buffer);  
  
            // 控制台打印出来  
            System.out.println("接收到来自" + clientChannel.socket().getRemoteSocketAddress() + "的信息:" + receivedString);  
  
            SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");  
            String f = format.format(new Date());  
            // 准备发送的文本  
            String sendString = "你好,客户端. @" + f + "，已经收到你的信息:" + receivedString;  
            buffer = ByteBuffer.wrap(sendString.getBytes("UTF-8"));  
            clientChannel.write(buffer);  
  
            // 设置为下一次读取或是写入做准备  
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);  
        }  

	}

	public void handleWrite(SelectionKey key) throws IOException {
//		  SocketChannel clientChannel = (SocketChannel) key.channel();  
//          ByteBuffer[] bfs = (ByteBuffer[]) key.attachment();  
//          if (bfs[bfs.length - 1].hasRemaining()) {  
//              clientChannel.write(bfs);  
//          } else {  
//              clientChannel.close();  
//
//          }  

	}

}
